import type { RequestFieldOption } from "../../req/RequestOption.js";

/**
 * 功能码
 */
export enum Operation {
    // 关闭连接
    Close = 0x00,
    // 启动信息
    Launch,
    // 加载资源
    LoadAsset,
    // 执行动作
    ExecAction,
}

const OpName: { [k in Operation]: string } = {
    [Operation.Close]: "关闭连接",
    [Operation.Launch]: "启动信息",
    [Operation.LoadAsset]: "加载资源",
    [Operation.ExecAction]: "执行动作",
};

function op(value: Operation): RequestFieldOption {
    return {
        name: "功能码 - " + OpName[value],
        kind: "u16",
        value,
        readonly: true,
    };
}

const crc: RequestFieldOption = {
    name: "校验码",
    kind: "u8",
    value: 0x12,
    readonly: true,
};

const length: RequestFieldOption = {
    name: "数据长度",
    kind: "custom",
    cb(ctx) {
        let len = 0;
        for (const key in ctx.lengths) {
            len += ctx.lengths[key]!;
        }
        len = len - 5;
        return [len & 0xff, (len >> 8) & 0xff];
    },
};

export const fields = {
    op: op,
    crc: crc,
    length: length,
} as const;
